package com.yyfax.ph.personal.authority.verifypassword;

import android.text.TextUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.secure.RSA;
import com.yyfax.ph.personal.authority.RSAPresenter;
import com.yyfax.ph.common.GlobalVariableConfig;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class VerifyPwdPresenter extends RSAPresenter<VerifyPwdModel, VerifyPwdPresenter.View> {
	private static final String TAG = VerifyPwdPresenter.class.getSimpleName();

	public static class Generator implements PresenterFactory<VerifyPwdPresenter> {
		@Override
		public VerifyPwdPresenter create() {
			return new VerifyPwdPresenter();
		}
	}

	public View mView;

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new VerifyPwdModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		void onVerify();

		void onVerifyFailure(String tips);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		VerifyPwdModel.VerifyPwd verify = (VerifyPwdModel.VerifyPwd) params;
		String keyRSA = GlobalVariableConfig.getKeyRSA();
		verify.password = RSA.encryptByPublicKey(verify.password, keyRSA);
		return verify;
	}

	public void verifyPwd(String pwd) {
		VerifyPwdModel.VerifyPwd verify = new VerifyPwdModel.VerifyPwd(pwd);

		execute(verify);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void verifyPwdResult(VerifyPwdModel.VerifyPwdResult result) {
		if (isResponseSuccess(result)) {
			mView.onVerify();
		} else {
			String tips = result.getMsg();
			mView.onVerifyFailure(TextUtils.isEmpty(tips) ? "密码验证失败!" : tips);
		}
	}
}
